<!DOCTYPE html>
<html lang="en">
<!--文章详情页-->
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="../assets/images/logo.png">
    <title>文章详情</title>

    <!-- 引入css：elementUi、bootstrap、bootstrap-icons、normalize统一规范、index -->
    <link rel="stylesheet" href="../node_modules/element-ui/lib/theme-chalk/index.css">
    <link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="../node_modules/bootstrap-icons/font/bootstrap-icons.min.css">
    <link rel="stylesheet" href="../assets/css/normalize.css">
    <link rel="stylesheet" href="../assets/css/detail.css">

    <!-- 引入JS：vue、elementUI、jQuery、bootstrap -->
    <script src="../node_modules/vue/dist/vue.min.js"></script>
    <script src="../node_modules/element-ui/lib/index.js"></script>
    <script src="../node_modules/jQuery/tmp/jquery.js"></script>
    <script src="../node_modules/bootstrap/dist/js/bootstrap.bundle.js"></script>
    <!-- 引入http-vue-loader：html页面中引入VUE组件需要的包 -->
    <script src="../node_modules/http-vue-loader/src/httpVueLoader.js"></script>
    <script src="../node_modules/axios/dist/axios.min.js"></script>
    <script src="../assets/js/common.js"></script>
</head>

<body>
<div id="app">
    <!-- 引入头部组件 -->
    <my-header></my-header>

    <section style="margin-top: 80px">
        <div class="container">
            <a href="#">
                <img src="../../assets/images/see.jpg" width="100%" alt="文章封面图"/>
            </a>
        </div>
    </section>

    <section class="mt-3">
        <div class="container">
            <div class="card" style="background-color: white;">
                <div class="card-body">
                    <div class="text-center">
                        <!-- 使用v-if防止数据未加载时的错误 -->
                        <h2 class="my-4" v-if="article">{{ article.articleName }}</h2>
                        <h2 class="my-4" v-else>加载中...</h2>

                        <p v-if="article">
                            <i class="bi bi-folder2-open opacity-50"></i>
                            <span class="card-text articleMsg">{{ article.articleTag }}</span>
                            <i class="bi bi-alarm opacity-50  ms-2"></i>
                            <span class="card-text articleMsg">{{ article.createTime }}</span>
                            <!-- 文章点赞按钮 -->
                            <button class="btn btn-link articleMsg ms-2"
                                    @click="toggleArticleStar">
                                <i :class="article.starred ? 'bi bi-hand-thumbs-up-fill text-primary' : 'bi bi-hand-thumbs-up opacity-50'"></i>
                                {{ article.articleStarNum }}
                            </button>
                            <i class="bi bi-book-half opacity-50 ms-2"></i>
                            <span class="card-text articleMsg">{{ article.articleReadCount }}</span>
                        </p>
                        <hr class="my-4"/>
                        <div v-if="article" v-html="article.articleContent" class="text-start">
                        </div>
                        <div v-else class="text-center text-muted">
                            <i class="bi bi-spinner bi-spin"></i> 正在加载文章内容...
                        </div>
                    </div>
                    <hr class="my-4"/>
                    <div>
                        <h3>相关文章</h3>
                        <ul class="list-group list-group-flush mb-3">
                            <!-- 显示加载状态 -->
                            <li v-if="loadingRelated" class="list-group-item" style="border: none;">
                                <i class="bi bi-spinner bi-spin"></i> 正在加载相关文章...
                            </li>

                            <!-- 显示相关文章列表 -->
                            <li
                                    class="list-group-item"
                                    style="border: none;"
                                    v-for="(item, index) in relatedArticles"
                                    :key="index"
                                    v-if="!loadingRelated && relatedArticles.length > 0"
                            >
                                &bull;
                                <a
                                        :href="'/detail.html?id=' + item.id"
                                        class="text-info article"
                                >
                                    {{ item.articleName }}
                                </a>
                            </li>

                            <!-- 没有相关文章时显示 -->
                            <li v-if="!loadingRelated && relatedArticles.length === 0" class="list-group-item"
                                style="border: none;">
                                &bull; 暂无相关文章
                            </li>

                            <!-- 加载失败时显示 -->
                            <li v-if="relatedError" class="list-group-item text-danger" style="border: none;">
                                &bull; 相关文章加载失败，请刷新页面重试
                            </li>
                        </ul>


                        <div style="background-color: #fafbfc;">
                            <div class="d-flex">
                                <img src="../../assets/images/p28.jpg" alt="用户头像" width="40px"
                                     class="rounded-circle m-2"/>
                                <input class="form-control h-75 mt-3" v-model="message" placeholder="请输入评论..."/>
                            </div>
                            <button type="button" @click="commont" class="btn btn-primary"
                                    style="width: 100px;margin-left: 55px;">发表评论
                            </button>
                        </div>

                        <hr/>


                        <div>
                            <!-- 评论列表 -->
                            <div v-for="(item, index) in messageList" :key="item.id">
                                <!-- 操作图标组（删除 + 回复 + 点赞） -->
                                <div class="comment-actions" style="float: right; margin-right: 10px;">
                                    <div class="delBtn" style="display: inline-block; cursor: pointer; margin-right: 10px;">
                                        <i class="bi bi-trash text-danger"></i>
                                    </div>
                                    <div class="replyBtn" style="display: inline-block; cursor: pointer;" @click="showReplyInput(index)">
                                        <i class="bi bi-chat-right-text text-primary"></i>
                                    </div>
                                    <!-- 评论点赞按钮 -->
                                    <div class="likeBtn" style="display: inline-block; cursor: pointer;" @click="toggleCommentStar(item.id, index)">
                                        <i :class="item.liked ? 'bi bi-heart-fill text-danger' : 'bi bi-heart opacity-50'"></i>
                                        <span>{{ item.likenum }}</span>
                                    </div>
                                </div>
                                <div class="d-flex">
                                    <img src="../../assets/images/p28.jpg" alt="用户头像" width="40px"
                                         class="rounded-circle m-2"/>
                                    <div class="mt-1">
                                          <span class="text-dark fw-bolder h6">{{ item.nickname }}:
                                          </span>
                                        <br/>
                                        <span>{{ item.createTime }}</span>
                                    </div>
                                </div>
                                <span style="margin-left: 55px;">{{ item.content }}</span>
                                <hr class="my-2"/>
                            </div>
                        </div>

                        <div class="my-3 ps-1 pe-4 d-flex justify-content-between">
                            <p>转载声明：本博客由波波老师创作。可自由转载、引用，
                                但需署名作者且注明文章出处。如转载至微信公众号，请在文末添加作者微信二维码。
                            </p>
                            <img src="../../assets/images/CSDN.png" alt="CSDN二维码" width="150px" height="130px"/>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<script>
    new Vue({
        el: "#app",
        data() {
            return {
                id: "", // 文章ID
                relatedArticles: [], // 相关文章列表
                loadingRelated: false,  // 相关文章加载状态
                relatedError: false,  // 相关文章加载错误状态
                message: "", // 评论输入内容
                messageList: [], // 评论列表

                userIp: "", // 用户IP（用于点赞限制）
                // 文章数据模型
                article: {
                    articleStarNum: 0, // 文章点赞数
                    starred: false, // 文章是否已点赞（前端状态标记）
                    id: null, // 文章ID
                    articleReadCount: 0, // 文章阅读量
                    articleName: '', // 文章标题
                    articleTag: '', // 文章标签
                    createTime: '', // 创建时间
                    articleContent: '' // 文章内容
                },
            }
        },
        methods: {
            // 统计文章浏览量
            countView() {
                if (this.id) {
                    this.$http.post(`/article/countView/${this.id}`)
                        .then(res => {
                            if (res.data.code === 200 && this.article) {
                                this.article.articleReadCount = res.data.data;
                            }
                        })
                        .catch(err => {
                            console.error("浏览量统计失败：", err);
                        });
                }
            },

            // 获取评论列表
            findallmessage() {
                let _this = this;
                _this.$http.get(`/comment/all/${_this.id}`).then(res => {
                    // 为每条评论初始化点赞状态
                    _this.messageList = res.data.data.map(comment => ({
                        ...comment,
                        liked: false, // 初始未点赞
                        showReply: false, // 回复输入框显示状态
                        replyContent: '' // 回复内容
                    }));
                }).catch(err => {
                    console.error("评论加载失败：", err);
                    this.$message.error("评论加载失败，请刷新重试");
                });
            },

            // 发表评论
            commont() {
                if (!this.message.trim()) {
                    this.$message.warning("评论内容不能为空");
                    return;
                }
                let _this = this;
                let params = {
                    "articleId": _this.id,
                    "content": _this.message,
                    "userId": 1,
                    "nickname": "xiaoyi",
                };
                _this.$http.post("/comment", params).then(res => {
                    if (res.data.code === 200) {
                        this.$message.success("评论成功");
                        _this.message = ""; // 清空输入框
                        _this.findallmessage(); // 重新加载评论列表
                    } else {
                        this.$message.error(res.data.msg || "评论失败");
                    }
                }).catch(err => {
                    console.error("评论提交失败：", err);
                    this.$message.error("网络错误，评论提交失败");
                });
            },

            // 文章点赞/取消点赞
            toggleArticleStar() {
                if (!this.article.id) return; // 文章ID不存在则不操作
                const articleId = this.article.id;
                const btn = event.currentTarget; // 获取点击的按钮元素
                btn.disabled = true; // 防止重复点击

                // 点赞状态更新处理函数
                const handleSuccess = (newStarNum, isStar) => {
                    this.article.articleStarNum = newStarNum;
                    this.article.starred = isStar;
                    btn.disabled = false;
                };

                if (this.article.starred) {
                    // 取消点赞
                    this.$http.post(`/article/unstar/${articleId}`).then(res => {
                        if (res.data.code === 200) {
                            handleSuccess(res.data.starNum, false);
                            this.$message.success("取消点赞成功");
                        } else {
                            this.$message.error(res.data.msg || "取消点赞失败");
                            btn.disabled = false;
                        }
                    }).catch(err => {
                        console.error("取消点赞失败：", err);
                        this.$message.error("网络错误，取消点赞失败");
                        btn.disabled = false;
                    });
                } else {
                    // 执行点赞（携带用户IP用于限制）
                    this.$http.post(`/article/star/${articleId}`).then(res => {
                        if (res.data.code === 200) {
                            handleSuccess(res.data.newStarNum, true);
                            this.$message.success("点赞成功");
                        } else if (res.data.code === 400) {
                            this.$message.warning("同一IP只能点赞一次哦～");
                            btn.disabled = false;
                        } else {
                            this.$message.error(res.data.msg || "点赞失败");
                            btn.disabled = false;
                        }
                    }).catch(err => {
                        console.error("点赞失败：", err);
                        this.$message.error("网络错误，点赞失败");
                        btn.disabled = false;
                    });
                }
            },

            // 评论点赞/取消点赞
            toggleCommentStar(commentId, index) {
                if (!commentId || index === undefined) return;
                const comment = this.messageList[index];
                const btn = event.currentTarget;
                btn.disabled = true;

                // 评论点赞状态更新处理函数
                const handleSuccess = (newLikeNum, isLiked) => {
                    comment.likenum = newLikeNum;
                    comment.liked = isLiked;
                    btn.disabled = false;
                };

                if (comment.liked) {
                    // 取消评论点赞
                    this.$http.post(`/comment/unstar/${commentId}`).then(res => {
                        if (res.data.code === 200) {
                            handleSuccess(res.data.likenum, false);
                            this.$message.success("取消评论点赞成功");
                        } else {
                            this.$message.error(res.data.msg || "取消评论点赞失败");
                            btn.disabled = false;
                        }
                    }).catch(err => {
                        console.error("取消评论点赞失败：", err);
                        this.$message.error("网络错误，取消失败");
                        btn.disabled = false;
                    });
                } else {
                    // 评论点赞
                    this.$http.post(`/comment/star/${commentId}`).then(res => {
                        if (res.data.code === 200) {
                            handleSuccess(res.data.likenum, true);
                            this.$message.success("评论点赞成功");
                        } else {
                            this.$message.error(res.data.msg || "评论点赞失败");
                            btn.disabled = false;
                        }
                    }).catch(err => {
                        console.error("评论点赞失败：", err);
                        this.$message.error("网络错误，点赞失败");
                        btn.disabled = false;
                    });
                }
            },

            // 显示回复输入框（预留方法）
            showReplyInput(index) {
                this.messageList[index].showReply = !this.messageList[index].showReply;
            },

            // 初始化文章信息
            initArticle() {
                if (!this.id) return;
                this.$http.get(`/article/${this.id}`).then(res => {
                    if (res.data.code === 200) {
                        this.article = {
                            ...res.data.data,
                            starred: false // 初始化为未点赞状态（可根据后端返回值调整）
                        };
                        // 加载相关文章
                        this.getRelatedArticles(this.article.articleType);
                    } else {
                        this.$message.error(res.data.msg || "文章加载失败");
                    }
                }).catch(err => {
                    console.error("文章加载失败：", err);
                    this.$message.error("网络错误，文章加载失败");
                });
            },

            // 获取相关文章
            getRelatedArticles(articleType) {
                this.loadingRelated = true;
                this.relatedError = false;
                try {
                    const params = new URLSearchParams();
                    params.append("currentId", this.id);
                    if (articleType) params.append("articleType", articleType);

                    this.$http.get(`/article/related?${params.toString()}`).then(res => {
                        this.loadingRelated = false;
                        if (res.data.code === 200) {
                            this.relatedArticles = res.data.data || [];
                        } else {
                            this.relatedError = true;
                            this.$message.error(res.data.msg || "相关文章加载失败");
                        }
                    }).catch(err => {
                        this.loadingRelated = false;
                        this.relatedError = true;
                        console.error("相关文章加载失败：", err);
                    });
                } catch (error) {
                    this.loadingRelated = false;
                    this.relatedError = true;
                    console.error("参数解析失败：", error);
                }
            },

            // 获取用户IP（用于点赞限制）
            getUserIp() {
                this.$http.post("/article/star/{articleId}").then(res => {
                    if (res.data.ip) {
                        this.userIp = res.data.ip;
                    }
                }).catch(err => {
                    console.warn("获取IP失败（不影响功能，仅影响点赞限制）：", err);
                });
            }
        },
        components: {
            'my-header': httpVueLoader('./common/header.vue')
        },
        mounted() {
            // 获取URL中的文章ID
            const searchParams = new URLSearchParams(location.search);
            this.id = searchParams.get('id');

            // 初始化操作
            if (this.id) {
                this.getUserIp(); // 获取用户IP
                this.initArticle(); // 加载文章信息
                this.findallmessage(); // 加载评论
                this.countView(); // 统计浏览量
            } else {
                this.$message.error("未找到文章ID");
            }
        }
    });
</script>

</body>

</html>